<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './dashboard/mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    theme() {
      return this.$store.state.settings.theme
    }

  },

  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    },
    theme: {
      handler(nval, oval) {
        if (oval !== undefined) {
          // this.setOptions(this.chartData)
        }
        console.log(nval, oval)// nval改变后的新数据，oval改变前的旧数据
      },
      deep: true, // 深度监听
      immediate: true// 立即执行
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },

  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions(data) {
      console.log(data, 'chartData: []')
      const xData = data.map((item) => {
        return item.name
      })
      const yData = data.map((item) => {
        return item.value
      })
      this.chart.setOption({
        color: [this.theme],
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: yData,
            type: 'bar'
          }
        ]
      })
    }

  }
}
</script>
